//
//  ViewController.swift
//  CoreDataDemo
//
//  Created by Apple Developer on 16/7/11.
//  Copyright © 2016年 ligang. All rights reserved.
//

import UIKit
import CoreData
class ViewController: UIViewController {

    @IBOutlet weak var ID: UITextField!
    @IBOutlet weak var age: UITextField!
    @IBOutlet weak var name: UITextField!
    
    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    /// 添加一条数据，是否重复，是否为空都需要自己控制检查，否则都能添加进数据库。
    @IBAction func addOne() {
        let _name = name.text
        let _age = age.text!
        let id = ID.text
        let person = NSEntityDescription.insertNewObjectForEntityForName("Person", inManagedObjectContext: appDelegate.managedObjectContext) as! Person
        person.name = _name
        person.age = Int(_age) ?? 0
        person.id = id
        appDelegate.saveContext()
        let alert = UIAlertController(title: "提示", message: "添加一条数据", preferredStyle: .Alert)
        alert.addTextFieldWithConfigurationHandler { (textField) in
            textField.placeholder = "userName"
        }
        alert.addAction(UIAlertAction(title: "确定", style: UIAlertActionStyle.Default, handler: { (alert) in
            
        }))
        presentViewController(alert, animated: true, completion: nil)
    }
    /// 修改age的数据
    @IBAction func ChangeSome() {
        let _name = name.text
        let _age = age.text!
        let _id = ID.text
        let fetchRequest = NSFetchRequest(entityName: "Person")
        let predicate = NSPredicate(format:"age=\(_age)")
        fetchRequest.predicate = predicate
        do{
            let persons = try appDelegate.managedObjectContext.executeFetchRequest(fetchRequest) as! [Person]
            for person in persons{
                person.name = _name
                person.id = _id
            }
            appDelegate.saveContext()
        }catch{
            NSLog("\(error)")
        }
    }
    /// 清空数据
    @IBAction func dropDB() {
        let fetchRequest = NSFetchRequest(entityName: "Person")
        do{
            let persons = try appDelegate.managedObjectContext.executeFetchRequest(fetchRequest) as! [NSManagedObject]
            for person in persons{
                appDelegate.managedObjectContext.deleteObject(person)
            }
            appDelegate.saveContext()
        }catch{
            NSLog("\(error)")
        }
    }
}

